<template>
  <div id="login-container">
    <div style="text-align: center;height: 50px">
      <h2>顺丰搬家</h2>
    </div>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="账号" prop="username">
        <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button @click="userRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import Cookies from 'js-cookie'
  import {login} from "@/api/user";
  import router from "@/router";
  export default {
    name: "login",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账户'));
      } else {
        callback();
      }
    };
    var validatePass2 =(rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { validator: validatePass, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      isLogin:false
    };
  },
  methods: {
    userRegister() {
      router.push({path:'/register'})
    },
    submitForm() {
      // 设置cookie键值对{'user': '...'}
      login(this.ruleForm).then(response=>{
        if (response) {
          const user = response.data
          const cookies = JSON.stringify(user)
          if (user.role === 0) {
            this.$message({
              type:'success',
              message:'登录成功'
            })
            Cookies.set("user",cookies,{ expires: 1 })
            this.$router.push({path: "/"});
          }
          if (user.role === 1) {
            Cookies.set("user",cookies,{expires: 1})
            this.$message({
              type:'success',
              message:'登录成功'
            })
            this.$router.push({path:"/normal"})
          }
        }
      })

    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
  }
</script>

<style scoped>
  body{
    margin: 0;
  }
  #login-container{
    padding: 40px;
    width: 400px;
    background: rgba(209, 234, 243, 0.8);

    -webkit-backdrop-filter: blur(2px);
    backdrop-filter: blur(2px);
    transform: translateZ(0);


    height: 290px;
    position: absolute;
    left: 50%;
    top: 25%;
    margin-left: -220px;
    border-radius: 5px;
  }
</style>
